package com.walker.kuyun.ui.activity

import android.os.Bundle
import android.view.View
import android.view.ViewStub
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.walker.kuyun.R
import com.walker.kuyun.databinding.ActivityMonthTmBinding
import com.walker.kuyun.ui.adapter.SearchTMAdapter
import com.walker.kuyun.viewmodel.MonthViewModel

class MonthTMActivity : BaseActivity<ActivityMonthTmBinding>() {
    private var partUrl: String = ""
    private lateinit var viewModel: MonthViewModel
    private lateinit var TMAdapter: SearchTMAdapter
    private var lastRefreshTime: Long = System.currentTimeMillis()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        partUrl = intent.getStringExtra("partUrl") ?: ""

        viewModel = ViewModelProvider(this).get(MonthViewModel::class.java)
        TMAdapter = SearchTMAdapter(this, viewModel.monthVideoList)

        val yearMonth = partUrl.replace("/", "")
        mBinding.run {
            toolbar.tvToolbar1Title.text = getString(
                R.string.year_month_anime,
                yearMonth.substring(0, 4).toInt(),
                yearMonth.substring(4, 6).toInt()
            )

            tmList.layoutManager = LinearLayoutManager(this@MonthTMActivity)
            tmList.setHasFixedSize(true)
            tmList.adapter = TMAdapter

            toolbar.ivToolbar1Back.setOnClickListener { finish() }
            refreshLayout.setColorSchemeResources(R.color.main_color)
            refreshLayout.setOnRefreshListener { //避免刷新间隔太短
                if (System.currentTimeMillis() - lastRefreshTime > 500) {
                    lastRefreshTime = System.currentTimeMillis()
                    viewModel.getMonthAnimeData(partUrl)
                } else {
                    refreshLayout.isRefreshing = false
                }
            }
        }

        viewModel.mldMonthAnimeList.observe(this, Observer {
            mBinding.refreshLayout.isRefreshing = false
            if (it) {
                hideLoadFailedTip()
            } else {
                showLoadFailedTip(
                    getString(R.string.load_data_failed_click_to_retry),
                    View.OnClickListener {
                        viewModel.getMonthAnimeData(partUrl)
                        hideLoadFailedTip()
                    })
            }
            TMAdapter.notifyDataSetChanged()
        })

        mBinding.refreshLayout.isRefreshing = true
        viewModel.getMonthAnimeData(partUrl)
    }

    override fun getBinding(): ActivityMonthTmBinding =
        ActivityMonthTmBinding.inflate(layoutInflater)

    override fun getLoadFailedTipView(): ViewStub = mBinding.loadFailedStub
}
